package org.springblade.modules.resource.utils;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.sc.ssp.uc.client.constant.UCConstant;
import com.iflytek.sc.ssp.uc.client.context.UCCasServiceContext;
import com.iflytek.sc.ssp.uc.client.util.SignUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class HttpUtil {
	private static final int TIMEOUT_IN_MILLIONS_TEN = 10000;

	private static String appSercert;

	public static boolean validateToken(String token) {
		String url = "/v2/user/validateToken";
		try {
			String res =  HttpUtil.postHandle(url, token);
			System.out.println("res=" + res);
			JSONObject jsonObject = JSONObject.parseObject(res);
			String code = jsonObject.getString("code");
			return "200".equals(code);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static String postHandle(String targetUrl, String token) throws Exception {
		UCConstant ucConstant = UCCasServiceContext.getUcConstant();
		appSercert = ucConstant.getAppSecret();
		String appCode = ucConstant.getAppCode();
		// 根据用户令牌获取用户信息
		String url = ucConstant.getResturl() + targetUrl;
		log.info("请求地址：{}，用户令牌token={}", url, token);

		TreeMap<String, String> signParams = new TreeMap<>();
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		signParams.put("time", time);
		signParams.put("appCode", appCode);
		signParams.put("token", token);

		// 生成待签名的参数
		String signData = SignUtil.produceData(signParams);
		String sign = SignUtil.md5Encode(signData + appSercert);
		log.debug("待签名的参数：{}，签名：{}", signData, sign);
		// 请求体
		Map<String, Object> paramData = new HashMap<>();
		paramData.put("token", token);
		// 请求头
		Map<String, String> headers = new HashMap<>();
		headers.put("time", time);
		headers.put("appCode", appCode);
		headers.put("sign", sign);
		// 请求返回列设置，不填默认为basic,legal
		headers.put("cm", "basic,credent,phone,legal");
		// doPost请求
		String result = HttpUtil.doPost(url, paramData, headers);
		log.info("请求成功，返回结果：{}", result);

		return result;
	}


	public static String doPost(String url, Map<String, Object> parameterData, Map<String, String> headers) throws Exception {
		//组装参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, Object> entry : parameterData.entrySet()) {
			sb.append("&" + entry.getKey() + "=" + entry.getValue().toString());
		}
		String param = sb.length() != 0 ? sb.substring(1) : "";

		//请求开始
		URL localURL = new URL(url);
		URLConnection connection = localURL.openConnection();
		HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setRequestMethod("POST");
		httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
		httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
		httpURLConnection.setConnectTimeout(TIMEOUT_IN_MILLIONS_TEN);
		httpURLConnection.setReadTimeout(TIMEOUT_IN_MILLIONS_TEN);


		for (Map.Entry<String, String> entry : headers.entrySet()) {
			//设置额外的请求头信息
			httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
		}

		OutputStream outputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer resultBuffer = new StringBuffer();
		String tempLine = null;

		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStreamWriter = new OutputStreamWriter(outputStream);
			outputStreamWriter.write(param);
			outputStreamWriter.flush();

			if (httpURLConnection.getResponseCode() >= 300) {
				log.error("访问" + url + "失败，http返回码" + httpURLConnection.getResponseCode() + "参数" + parameterData);
				throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
			}

			inputStream = httpURLConnection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);

			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}

		} finally {
			if (outputStreamWriter != null) outputStreamWriter.close();
			if (outputStream != null) outputStream.close();
			if (reader != null) reader.close();
			if (inputStreamReader != null) inputStreamReader.close();
			if (inputStream != null) inputStream.close();
		}

		return resultBuffer.toString();
	}

}
